<template>
  <div class="dataVisual-body">
    <div class="wpbox">
      <div class="bnt">
        <div class="topbnt_left fl">
          <ul>
            <li><a href="/index">返回系统</a></li>
          </ul>
        </div>
        <h1 class="tith1 fl">管道监测设备数据分析</h1>
        <div class="fr topbnt_right">
          <ul>
            <li><a href="#" @click="touchFullScreen">{{ fullscreen }}</a></li>
            <li><a href="#">语音播报</a></li>
            <li><a href="#">报警提醒</a></li>
            <li class="active"><a href="#">报警静音</a></li>
          </ul>
        </div>
      </div>
      <el-row :gutter="5" style="width: 96%; height: 100%; margin-left: 2%;">
        <el-col :span="6" style="height: 100%">
          <div class="aleftboxttop">
            <h2 class="tith2">设备报警事件统计</h2>
            <div class="lefttoday_tit" style=" height:8%">
<!--              <p class="fl">地区：银滩花园</p>-->
              <p class="fr">时间段：{{ gasEventThisYearStatistics.thisMonth }}</p>
            </div>
            <div class="lefttoday_number">
              <div class="widget-inline-box text-center fl">
                <p>总报警数</p>
                <h3 class="ceeb1fd">{{ gasEventThisYearStatistics.monthIi + gasEventThisYearStatistics.monthPosition + gasEventThisYearStatistics.monthAngle }}</h3>
                <h4 class="text-muted pt6">
                  环比
                  <span v-show="gasEventThisYearStatistics.monthIi + gasEventThisYearStatistics.monthPosition + gasEventThisYearStatistics.monthAngle > 0">
                    <img v-show="gasEventThisYearStatistics.monthIi + gasEventThisYearStatistics.monthPosition + gasEventThisYearStatistics.monthAngle > gasEventThisYearStatistics.lastMonthIi + gasEventThisYearStatistics.lastMonthPosition + gasEventThisYearStatistics.lastMonthAngle" src="@/assets/images/visual/dataVisual/iconup.png" height="16" />
                    <img v-show="gasEventThisYearStatistics.monthIi + gasEventThisYearStatistics.monthPosition + gasEventThisYearStatistics.monthAngle < gasEventThisYearStatistics.lastMonthIi + gasEventThisYearStatistics.lastMonthPosition + gasEventThisYearStatistics.lastMonthAngle" src="@/assets/images/visual/dataVisual/icondown.png" height="16" />
                  </span>
                  {{ gasEventThisYearStatistics.lastMonthIi + gasEventThisYearStatistics.lastMonthPosition + gasEventThisYearStatistics.lastMonthAngle == 0 ? '-' : (100*(gasEventThisYearStatistics.monthIi + gasEventThisYearStatistics.monthPosition + gasEventThisYearStatistics.monthAngle)/(gasEventThisYearStatistics.lastMonthIi + gasEventThisYearStatistics.lastMonthPosition + gasEventThisYearStatistics.lastMonthAngle)).toFixed(2) + '%' }}
                </h4>
              </div>
              <div class="widget-inline-box text-center fl">
                <p>震动报警</p>
                <h3 class="c24c9ff">{{ gasEventThisYearStatistics.monthIi }}</h3>
                <h4 class="text-muted pt6">
                  环比
                  <span v-show="gasEventThisYearStatistics.lastMonthIi > 0">
                    <img v-show="gasEventThisYearStatistics.monthIi > gasEventThisYearStatistics.lastMonthIi" src="@/assets/images/visual/dataVisual/iconup.png" height="16" />
                    <img v-show="gasEventThisYearStatistics.monthIi < gasEventThisYearStatistics.lastMonthIi" src="@/assets/images/visual/dataVisual/icondown.png" height="16" />
                  </span>
                  {{ gasEventThisYearStatistics.lastMonthIi == 0 ? '-' : (100*gasEventThisYearStatistics.monthIi/gasEventThisYearStatistics.lastMonthIi).toFixed(2) + '%' }}
                </h4>
              </div>
              <div class="widget-inline-box text-center fl">
                <p>位移报警</p>
                <h3 class="cffff00">{{ gasEventThisYearStatistics.monthPosition }}</h3>
                <h4 class="text-muted pt6">
                  环比
                  <span v-show="gasEventThisYearStatistics.lastMonthPosition > 0">
                    <img v-show="gasEventThisYearStatistics.monthPosition > gasEventThisYearStatistics.lastMonthPosition" src="@/assets/images/visual/dataVisual/iconup.png" height="16" />
                    <img v-show="gasEventThisYearStatistics.monthPosition < gasEventThisYearStatistics.lastMonthPosition" src="@/assets/images/visual/dataVisual/icondown.png" height="16" />
                  </span>
                  {{ gasEventThisYearStatistics.lastMonthPosition == 0 ? '-' : (100*gasEventThisYearStatistics.monthPosition/gasEventThisYearStatistics.lastMonthPosition).toFixed(2) + '%' }}
                </h4>
              </div>
              <div class="widget-inline-box text-center fl">
                <p>倾斜报警</p>
                <h3 class="c11e2dd">{{ gasEventThisYearStatistics.monthAngle }}</h3>
                <h4 class="text-muted pt6">
                  环比
                  <span v-show="gasEventThisYearStatistics.lastMonthAngle > 0">
                    <img v-show="gasEventThisYearStatistics.monthAngle > gasEventThisYearStatistics.lastMonthAngle" src="@/assets/images/visual/dataVisual/iconup.png" height="16" />
                    <img v-show="gasEventThisYearStatistics.monthAngle < gasEventThisYearStatistics.lastMonthAngle" src="@/assets/images/visual/dataVisual/icondown.png" height="16" />
                  </span>
                  {{ gasEventThisYearStatistics.lastMonthAngle == 0 ? '-' : (100*gasEventThisYearStatistics.monthAngle/gasEventThisYearStatistics.lastMonthAngle).toFixed(2) + '%' }}
                </h4>
              </div>
            </div>
            <!-- lefttoday_number end -->
          </div>
          <div class="aleftboxtmidd">
            <h2 class="tith2">设备情况统计</h2>
<!--            <div class="lefttoday_tit height ht">-->
<!--              <p class="fl">地区：银滩花园</p>-->
<!--              <p class="fr">时间段：2020-06月</p>-->
<!--            </div>-->
            <div id="aleftboxtmidd" class="aleftboxtmiddcont"></div>
          </div>
          <div class="aleftboxtbott">
            <h2 class="tith2">近两月事件对比分析</h2>
            <!--<div class="lefttoday_tit height">
              <p class="fl">地区：银滩花园</p>
              <p class="fr">时间段：{{ gasEventThisYearStatistics.lastMonth }}至{{ gasEventThisYearStatistics.thisMonth }}</p>
            </div>-->
            <div id="aleftboxtbott" class="aleftboxtbott_cont"></div>
          </div>
        </el-col>
        <el-col :span="12" style="height: 100%">
          <div style="height: 100%">
            <div class="amiddboxttop">
              <h2 class="tith2" style="padding-top: 1.3%; margin-top: 3%;">设备分布</h2>
              <div id="centerMap" class="amiddboxttop_map" style="">
              </div>
            </div>
          </div>
        </el-col>
        <el-col :span="6" style="height: 100%">
          <div style="height: 100%">
            <div class="arightboxtop">
              <h2 class="tith2">最新报警</h2>
              <div class="lefttoday_tit">
<!--                <p class="fl">地区：银滩花园</p>-->
                <p class="fr">时间段：{{ parseTime(now, '{y}-{m}-{d}') }}</p>
              </div>
              <div class="zhtc_table_title">
                <div>设备信息</div>
                <!-- 车牌 -->
                <div>报警时间</div>
                <!-- 进场时间 -->
                <div>报警值</div>
                <!-- 图片 -->
                <div>类型</div>
                <!-- 车辆类型 -->
              </div>
              <div id="zhtc_table" class="left2_table">
                <ul>
                  <li v-for="(item, i) in gasRecentEventList" :class="i % 2 == 0 ? 'bg' : ''">
                    <div class="zhtc_table_li_content">
                      <div>
                        {{ item.clientName }}
                        <br>
                        {{ '(' + item.clientNo + ')' }}
                      </div>
                      <div>{{ item.eventTime}}</div>
                      <div>{{ item.alertValue }}</div>
                      <div>{{ eventType[item.eventType] }}</div>
                    </div>
                  </li>
                </ul>
              </div>

            </div>
            <div class="arightboxbott">
              <h2 class="tith2 ">30日事件趋势</h2>
              <div class="lefttoday_tit">
<!--                <p class="fl">地区：银滩花园</p>-->
                <p class="fr">时间段：{{ gasThirtyDaysTrendData.days[0] }} 至 {{ gasThirtyDaysTrendData.days[gasThirtyDaysTrendData.days.length-1] }}</p>
              </div>
              <div id="arightboxbott" class="arightboxbottcont"></div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>


<script>
import '@/assets/styles/visual/dataVisual.css'
import echarts from 'echarts'
import { gasDataVisual, thirtyDaysGasEventTrend } from "@/api/device/gasStatistics";
import screenfull from "screenfull";

export default {
  name: "GasStatistics",
  data() {
    return {
      now: new Date(),
      eventType: {
        'Ii': '震动',
        'position': '位移',
        'angle': '倾斜'
      },
      onlineIcon: require('@/assets/images/visual/dataVisual/device-online.png'),
      offlineIcon: require('@/assets/images/visual/dataVisual/device-offline.png'),
      dormancyIcon: require('@/assets/images/visual/dataVisual/device-dormancy.png'),
      map: null,
      clientMarkerMap: null,
      baiduMapInfoWindow: null,
      gasClientList: [],
      gasClientStat: {
        onlineCount: 0,
        offlineCount: 0,
        dormancy: 0,
      },
      gasRecentEventList: [],
      gasEventThisYearStatistics: {
        thisMonth: '####年##月',
        lastMonth: '####年##月',
        todayPosition: 0,
        todayAngle: 0,
        todayIi: 0,
        monthPosition: 0,
        monthIi: 0,
        monthAngle: 0,
        lastMonthPosition: 0,
        lastMonthIi: 0,
        lastMonthAngle: 0,
        yearPosition: 0,
        yearAngle: 0,
        yearIi: 0,
        totalPosition: 0,
        totalAngle: 0,
        totalIi: 0
      },
      gasEventStat: {
        totalCount: 0,
        IiCount: 0,
        positionCount: 0,
        angleCount: 0
      },
      gasThirtyDaysTrendData: {
        days: [],
        IiList: [],
        totalList: [],
        positionList: [],
        angleList: []
      },
      deviceStatisticsChart: null,
      recentTwoMonthStatChart: null,
      deviceStatisticsChartOption: null,
      recentTwoMonthStatChartOption: null,
      gasThirtyDaysTrendChart: null,
      gasThirtyDaysTrendChartOption: null,
      fullscreen: '全屏显示'
    };
  },
  created() {
    this.$nextTick(() => {
      this.initCharts();
      this.getGasDataVisual()
      this.getGasThirtyDaysEventTrend()
      this.initCenterMap();
      this.$store.dispatch('websocketSubscribe', {'topic': 'gasEventMsg'})
      this.$store.dispatch('wsAddCallback', {'topic': 'gasEventMsg',  'cb': this.wsOnMessage});
    })
  },
  mounted: function () {
    const that = this;
    this.$nextTick(() => {
      window.addEventListener('resize',function(){
        // 重新定义charts
        that.deviceStatisticsChart.resize();
        that.recentTwoMonthStatChart.resize();
        that.gasThirtyDaysTrendChart.resize();
      })
    })
  },
  destroyed() {
    this.$store.dispatch('wsRemoveCallback', {'topic': 'gasEventMsg',  'cb': _this.wsOnMessage});
  },
  methods: {
    touchFullScreen(){
      if(this.fullscreen == '全屏显示'){
        this.fullscreen = '取消全屏';
      }else{
        this.fullscreen = '全屏显示';
      }
      screenfull.toggle()
    },
    wsOnMessage(msg){
      console.log("收到回调消息：", msg)
      let _this = this;
      if(msg.topic == 'configChange' && msg.clientNo == _this.client.clientNo){
        let data = msg.data
        let _clientInfo = {
          config: data.config ? JSON.parse(JSON.stringify(data.config)) : {},
          centerConfig: data.centerConfig ? JSON.parse(JSON.stringify(data.centerConfig)) : {},
          info: data.info ? JSON.parse(JSON.stringify(data.info)) : {},
          status: data.status ? JSON.parse(JSON.stringify(data.status)) : _this.clientInfo.status,
          mems: data.mems ? JSON.parse(JSON.stringify(data.mems)) : _this.clientInfo.mems,
          screenshot: data.screenshot ? data.screenshot : _this.clientInfo.screenshot, // 截屏图片
        }
        _this.client = data.client ? data.client : _this.client

        _this.clientInfo = _clientInfo;
        _this.synchronized = true;
        _this.configFetching = false;
      }else if(msg.topic == 'devStatus' && msg.clientNo == _this.client.clientNo){
        let data = msg.data
        console.log(data)
        let _clientInfo = {
          config: _this.clientInfo.config,
          centerConfig: _this.clientInfo.centerConfig,
          info: _this.clientInfo.info,
          status: data ? JSON.parse(JSON.stringify(data)) : _this.clientInfo.status,
          mems: _this.clientInfo.mems,
          screenshot: _this.clientInfo.screenshot
        }
        _this.clientInfo = _clientInfo;
        _this.statusFetching = false;
      }else if(msg.topic == 'terminalResult' && msg.clientNo == _this.client.clientNo){
        _this.cmdResult += msg.data + "\n";
        this.$nextTick(() => {
          setTimeout(() => {
            const textarea = document.getElementById('cmdResultTextarea');
            textarea.scrollTop = textarea.scrollHeight;
          }, 13)
        })
      }
    },
    getGasDataVisual(){
      gasDataVisual().then(response => {
        this.gasClientList = response.data.gasClientList;
        this.gasRecentEventList = response.data.gasEventList;
        this.gasEventThisYearStatistics = response.data.gasEventThisYearStatistics;
        this.initRecentTwoMonthStat();
        this.initClientMarkers();
      });
    },
    getGasThirtyDaysEventTrend(){
      thirtyDaysGasEventTrend().then(response => {
        this.gasThirtyDaysTrendData = response.data;
        this.initThirtyDaysGasEventTrend();
      });
    },
    initCenterMap(){
      let _this = this;
      _this.map = new BMapGL.Map("centerMap");
      _this.map.addControl(new BMapGL.MapTypeControl({mapTypes: [BMAP_NORMAL_MAP, BMAP_EARTH_MAP]}));          //2D图，卫星图
      // let point = new BMapGL.Point(116.404, 39.915);  // 创建点坐标
      //    map.centerAndZoom(point, 15);                 // 初始化地图，设置中心点坐标和地图级别
      _this.map.centerAndZoom(new BMapGL.Point(103.388611,35.563611), 5);// 初始化地图，设置中心点坐标和地图级别，全国地图
      _this.map.enableScrollWheelZoom(true);     //开启鼠标滚轮缩放
      // _this.map.setMapStyleV2({ styleJson: _this.baiduMapStyle() });
      // _this.map.setMapType(BMAP_EARTH_MAP);
    },
    initClientMarkers(){
      let _this = this;
      let clientList = this.gasClientList;
      _this.map.clearOverlays();
      _this.clientMarkerMap = {};
      _this.gasClientStat = {
        onlineCount: 0,
        offlineCount: 0,
        dormancyCount: 0
      }
      for(let i in clientList){
        let client = clientList[i];
        _this.addMapMarker(client);
        if(client.clientStat == 'online'){
          _this.gasClientStat.onlineCount ++;
        }else if(client.clientStat == 'offline'){
          _this.gasClientStat.offlineCount ++;
        }else if(client.clientStat == 'dormancy'){
          _this.gasClientStat.dormancyCount ++;
        }
      }
      this.initDeviceStatistics();
    },
    addMapMarker(client){
      let _this = this;
      // 创建设备图标
      let pic = client.clientStat == 'online' ? _this.onlineIcon : client.clientStat == 'dormancy' ? _this.dormancyIcon : _this.offlineIcon;
      // 创建Marker标注，使用设备图标
      let longitude = client.longitude;
      let latitude = client.latitude;
      let pt = new BMapGL.Point(longitude, latitude);
      let myIcon = new BMapGL.Icon(pic, new BMapGL.Size(40, 40));
      // myIcon.setImageOffset(new BMapGL.Size(15, 20));
      let marker = new BMapGL.Marker(pt, {
        icon: myIcon
      });
      // 将标注添加到地图
      _this.map.addOverlay(marker);
      marker.addEventListener("click", function(){
        let opts = {
          width : 200,     // 信息窗口宽度
          height: 100,     // 信息窗口高度
          title : client.clientName , // 信息窗口标题
          message: client.clientName
        }
        if(_this.baiduMapInfoWindow){
          _this.baiduMapInfoWindow.close();
        }
        let text = "设备地址：" + client.address + "</br>" + "经纬度：" + client.longitude + "," + client.latitude + "</br>" + "设备编号：" + client.clientNo;
        _this.baiduMapInfoWindow = new BMapGL.InfoWindow(text, opts);  // 创建信息窗口对象
        _this.map.openInfoWindow(_this.baiduMapInfoWindow, pt);// 打开信息窗口
        _this.map.centerAndZoom(marker.getPosition(), 11);
      });
      _this.clientMarkerMap[client.clientNo] = marker;
    },
    initCharts(){
      this.deviceStatisticsChart = echarts.init(document.getElementById('aleftboxtmidd'));
      this.recentTwoMonthStatChart = echarts.init(document.getElementById('aleftboxtbott'));
      this.gasThirtyDaysTrendChart = echarts.init(document.getElementById('arightboxbott'));
    },
    initDeviceStatistics(){
      let _this = this;
      _this.deviceStatisticsChartOption = {
        backgroundColor: 'rgba(1,202,217,.2)',
        legend:{
          orient: 'vertical', // 'vertical'
          x: 'left', // 'center' | 'left' | {number},
          y: '80', // 'center' | 'bottom' | {number}
          padding: 10,    // [5, 10, 15, 20]
          itemGap: 20,
          textStyle: {color: '#c3cad9'},
        },
        tooltip: {
          trigger: 'item',
          formatter: "{b} : {c} ({d}%)"
        },
        visualMap: {
          show: false,
          min: 500,
          max: 600,
          inRange: {
            //colorLightness: [0, 1]
          }
        },
        series: [{
          name: '在线状态',
          type: 'pie',
          radius: '50%',
          selectedMode: 'single',
          selectedOffset: 10,
          clockwise: true,
          center: ['50%', '50%'],
          color: ['#33ff99', '#43cadd', '#ff6464'], //'#FBFE27','rgb(11,228,96)','#FE5050'
          data: [{
            value: _this.gasClientStat.onlineCount,
            name: '在线',
          },{
            value: _this.gasClientStat.offlineCount,
            name: '离线',
          },
            {
              value: _this.gasClientStat.dormancyCount,
              name: '休眠'
            }
          ].sort(function(a, b) {
            return a.value - b.value
          }),
          roseType: 'radius',
          label: {
            normal: {
              // formatter: ['{c|{b}{d}%}', '{b|{b}}'].join('\n'),
              formatter: ['{b|{b}{d}%}', '{c|{c}台}'].join('\n'),
              rich: {
                b: {
                  color: '#d9efff',
                  fontSize: 15,
                  height: 40
                },
                c: {
                  color: '#fff',
                  fontSize: 14,
                  fontWeight:'bold',
                  lineHeight: 5
                },
              },
            }
          },
          labelLine: {
            normal: {
              backgroundColor:'yellow',
              borderColor:'skyblue',
              borderWidth:10,
              lineStyle: {
                borderColor:'skyblue',
                borderWidth:10,
                backgroundColor:'yellow',
              }
            },
          }
        }]
      };
      _this.deviceStatisticsChart.setOption(_this.deviceStatisticsChartOption);
    },
    initRecentTwoMonthStat(){
      let _this = this;
      _this.recentTwoMonthStatChartOption = {
        color: ['#7ecef4'],
        backgroundColor: 'rgba(1,202,217,.2)',
        legend: {
          right: 10,
          top: 5,
          textStyle: {
            fontSize: 10,
            color: 'rgba(255,255,255,.6)'
          },
          data: [ _this.gasEventThisYearStatistics.lastMonth, _this.gasEventThisYearStatistics.thisMonth ]
        },
        grid: {
          left: 20,
          right: 20,
          top: 30,
          bottom: 2,
          containLabel: true
        },

        xAxis: {
          type: 'value',
          axisLine: {
            lineStyle: {
              color: 'rgba(255,255,255,.2)'
            }
          },
          splitLine: {
            lineStyle: {
              color: 'rgba(255,255,255,0)'
            }
          },
          axisLabel: {
            color: "rgba(255,255,255,0)"
          },
          boundaryGap: [0, 0.01]
        },
        yAxis: {
          type: 'category',

          axisLine: {
            lineStyle: {
              color: 'rgba(255,255,255,.5)'
            }
          },
          splitLine: {
            lineStyle: {
              color: 'rgba(255,255,255,.1)'
            }
          },
          axisLabel: {
            color: "rgba(255,255,255,.5)"
          },
          data: ['震动', '位移', '倾斜']
        },
        series: [{
          name: _this.gasEventThisYearStatistics.lastMonth,
          type: 'bar',
          barWidth: 15,
          label: {
            show: true,
            position: 'inside'
          },
          itemStyle: {
            normal: {
              color: new echarts.graphic.LinearGradient(
                1, 0, 0, 1, [{
                  offset: 0,
                  color: 'rgba(77,114,217,.7)'
                }, {
                  offset: 1,
                  color: 'rgba(117,72,159,.7)'
                }]
              )
            }
          },
          data: [ _this.gasEventThisYearStatistics.lastMonthIi, _this.gasEventThisYearStatistics.lastMonthPosition, _this.gasEventThisYearStatistics.lastMonthAngle ]
        }, {
          name: _this.gasEventThisYearStatistics.thisMonth,
          type: 'bar',
          barWidth: 15,
          label: {
            show: true,
            position: 'inside'
          },
          itemStyle: {
            normal: {
              color: new echarts.graphic.LinearGradient(
                1, 0, 0, 1, [{
                  offset: 0,
                  color: 'rgba(230,253,139,.7)'
                }, {
                  offset: 1,
                  color: 'rgba(41,220,205,.7)'
                }]
              )
            }
          },
          data: [ _this.gasEventThisYearStatistics.monthIi, _this.gasEventThisYearStatistics.monthPosition, _this.gasEventThisYearStatistics.monthAngle ]
        }]
      };
      _this.recentTwoMonthStatChart.setOption(_this.recentTwoMonthStatChartOption);
    },
    initThirtyDaysGasEventTrend(){
      let _this = this;
      _this.gasThirtyDaysTrendChartOption = {
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          textStyle: {
            fontSize: 10,
            color: 'rgba(255,255,255,.6)'
          },
          data: ['震动', '位移','倾斜','总报警数']
        },
        toolbox: {
          show: true,
          feature: {
            saveAsImage: { show: true }
          }
        },
        calculable: true,
        xAxis: [
          {
            type: 'category',
            data: _this.gasThirtyDaysTrendData.days
          }
        ],
        yAxis: [
          {
            type: 'value'
          },
          {
            type: 'value',
            name: '事件数',
            nameTextStyle: {
              color: '#ffffff',
            },
            splitLine:{show: false},//去除网格线
            axisLine: {
              show: false,
              lineStyle: {
                color: '#ffffff'
              }
            },
            axisTick: {show: false},
            axisLabel: {
              margin: 2,
              interval: 10,
              color: '#ffffff',
            }
          }
        ],
        series: [
          {
            name: '震动',
            type: 'bar',
            color:['#0099ff'],
            data: _this.gasThirtyDaysTrendData.IiList,
          },
          {
            name: '位移',
            type: 'bar',
            color:['#ff0000'],
            data: _this.gasThirtyDaysTrendData.positionList,
            markLine: {
            }
          },
          {
            name: '倾斜',
            type: 'bar',
            color:['#fff200'],
            data: _this.gasThirtyDaysTrendData.angleList,
          },
          {
            name: '总报警数',
            type: 'line',
            color:['#0de7ef'],  //折线条的颜色
            smooth: true,
            yAxisIndex: 1,
            itemStyle: {
              hadowBlur: 2,
            },
            data:  _this.gasThirtyDaysTrendData.totalList,
          },
        ]
      };
      _this.gasThirtyDaysTrendChart.setOption(_this.gasThirtyDaysTrendChartOption)
    },
  }
};
</script>
